package com.shuziren.webscoket;

import com.shuziren.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class UserSessionRegistry {

    @Autowired
    private RedisService redisService;

    // 存储用户最新会话
    private final Map<String, WebSocketSession> userSessionMap = new ConcurrentHashMap<>();
    //注册会话
    public void registerSession(String token,String username, WebSocketSession session){
        WebSocketSession oldSession = userSessionMap.get(username);
        // 只有在oldSession不为null时才进行后续操作，避免首次连接时空指针异常
//        if (oldSession != null && !oldSession.getId().equals(session.getId())) {
//            try {
//                // 如果有旧连接且与当前连接不同，关闭旧连接
//                oldSession.close(CloseStatus.POLICY_VIOLATION.withReason("账号已在其他设备登录"));
//                redisService.del("OnlineUser:"+username);
//                redisService.set("OnlineUser:"+username, token, 60*60*24*7L);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
        // 注册/更新当前用户的session
        userSessionMap.put(username, session);
    }

    // 注销会话
    public void unregisterSession(String userId, String sessionId) {
        if (userSessionMap.containsKey(userId) && userSessionMap.get(userId).getId().equals(sessionId)) {
            userSessionMap.remove(userId);
        }
    }

    // 强制下线指定用户
    public void forceLogout(String userId, String reason) {
        WebSocketSession session = userSessionMap.get(userId);
        if (session != null && session.isOpen()) {
            try {
                // 发送强制下线通知
                session.sendMessage(new TextMessage("KICKED_OUT"));
                // 关闭连接
                session.close(CloseStatus.POLICY_VIOLATION.withReason(reason));
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 清理会话
                userSessionMap.remove(userId);
            }
        }
    }
}
